package com.bigdata.utils;

import com.alibaba.druid.support.logging.Log;
import com.alibaba.druid.support.logging.LogFactory;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.*;

import java.io.IOException;
import java.io.Writer;

/**
 * @ClassNameJsonUtils
 * @Description
 * @Author lly
 * @Date2020/3/15 9:35
 * @Version V1.0
 **/
public class JsonUtils {
    private static Log log = LogFactory.getLog(JsonUtils.class);

    public static Object toObject(String json, TypeReference<?> typeReference) {
        try {
            ObjectMapper mapper = new ObjectMapper();
            mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
            mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
            mapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true);
            return mapper.readValue(json, typeReference);
        } catch (Exception e) {
            log.error("Parse JSON String Error: " + json, e);
        }
        return null;
    }

    public static Object toObject(String json, JavaType javaType) {
        try {
            ObjectMapper mapper = new ObjectMapper();
            mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
            mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
            mapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true);
            return mapper.readValue(json, javaType);
        } catch (Exception var3) {
            log.error("Parse JSON String Error: " + json, var3);
            return null;
        }
    }

    public static void writeValue(Writer writer, Object value) {
        try {
            ObjectMapper mapper = new ObjectMapper();
            mapper.writeValue(writer, value);
        } catch (IOException e) {
            log.error("Generate JSON String Error: " + value, e);
        }
    }

    public static <T> T toObject(String json, Class<T> valueType) {
        try {
            ObjectMapper mapper = new ObjectMapper();
            return mapper.readValue(json, valueType);
        } catch (Exception e) {
            log.warn("Parse JSON String Error: " + json, e);
        }
        return null;
    }
}
